<template>
    <div class="basic-info-container">
        <el-container>
            <el-header>
                <div class="header-content">
                    <h2>基础信息维护</h2>
                    <div class="date-selector">
                        <el-date-picker v-model="评测日期" type="date" placeholder="选择评测日期" format="YY-MM-DD"
                            value-format="YYYY-MM-DD" @change="handleDateChange" style="width: 200px" />
                    </div>
                </div>
            </el-header>
            <el-main>
                <!-- 基础信息列表 -->
                <el-card class="list-card" shadow="never">
                    <template #header>
                        <div class="card-header">
                            <span>基础信息列表</span>
                            <el-button type="primary" @click="showAddDialog = true">新增</el-button>
                        </div>
                    </template>
                    <el-table :data="basicInfoList" border stripe v-loading="loading" style="width: 100%">
                        <el-table-column prop="牌别" label="牌别" width="150" />
                        <el-table-column prop="批次" label="批次" width="150" />
                        <el-table-column prop="日期" label="日期" width="150">
                            <template #default="{ row }">
                                {{ formatDateYY(row.日期) }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="150">
                            <template #default="{ row }">
                                <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
                                <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <!-- 新增/编辑对话框 -->
                <el-dialog :title="dialogTitle" v-model="showAddDialog" width="500px">
                    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                        <el-form-item label="牌别" prop="牌别">
                            <el-input v-model="form.牌别" placeholder="请输入牌别" clearable />
                        </el-form-item>

                        <el-form-item label="批次" prop="批次">
                            <el-input v-model="form.批次" placeholder="请输入批次" clearable />
                        </el-form-item>

                        <el-form-item label="日期" prop="日期">
                            <el-date-picker v-model="form.日期" type="date" placeholder="选择日期" format="YY-MM-DD"
                                value-format="YYYY-MM-DD" style="width: 100%" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <el-button @click="showAddDialog = false">取消</el-button>
                        <el-button type="primary" :loading="submitting" @click="handleSubmit">确定</el-button>
                    </template>
                </el-dialog>

                <div class="nav-section">
                    <el-button type="success" @click="goToEvaluation" style="width: 100%">
                        前往评价页面
                    </el-button>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { createBasicInfo, getBasicInfoByDate } from '../api/api';

const router = useRouter();
const formRef = ref(null);
const loading = ref(false);
const submitting = ref(false);
const 评测日期 = ref('');
const basicInfoList = ref([]);
const showAddDialog = ref(false);
const editingRow = ref(null);
const dialogTitle = ref('新增基础信息');

const form = reactive({
    牌别: '',
    批次: '',
    日期: ''
});

const rules = {
    牌别: [
        { required: true, message: '请输入牌别', trigger: 'blur' }
    ],
    批次: [
        { required: true, message: '请输入批次', trigger: 'blur' }
    ],
    日期: [
        { required: true, message: '请选择日期', trigger: 'change' }
    ]
};

// 格式化日期为YY-MM-DD格式
const formatDateYY = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear().toString().slice(-2);
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 获取今天的日期
const getToday = () => {
    const today = new Date();
    评测日期.value = today.toISOString().split('T')[0];
};

// 根据评测日期获取基础信息列表
const fetchBasicInfoList = async () => {
    if (!评测日期.value) return;

    loading.value = true;
    try {
        const res = await getBasicInfoByDate(评测日期.value);
        if (res.success) {
            basicInfoList.value = res.data || [];
        } else {
            ElMessage.error(res.message || '获取基础信息失败');
        }
    } catch (error) {
        console.error('获取基础信息失败:', error);
        ElMessage.error('获取基础信息失败，请重试');
    } finally {
        loading.value = false;
    }
};

// 评测日期变化
const handleDateChange = () => {
    fetchBasicInfoList();
};

// 编辑行
const handleEdit = (row) => {
    editingRow.value = row;
    form.牌别 = row.牌别;
    form.批次 = row.批次;
    form.日期 = row.日期;
    dialogTitle.value = '编辑基础信息';
    showAddDialog.value = true;
};

// 删除行
const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除牌别"${row.牌别}"、批次"${row.批次}"的基础信息吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        ElMessage.warning('删除功能需要后端API支持，请在后端添加删除接口');
        // TODO: 实现删除功能，需要后端API支持
    } catch (error) {
        // 用户取消
    }
};

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
        if (valid) {
            if (!评测日期.value) {
                ElMessage.warning('请先选择评测日期');
                return;
            }

            submitting.value = true;
            try {
                const res = await createBasicInfo({
                    评测日期: 评测日期.value,
                    牌别: form.牌别,
                    批次: form.批次,
                    日期: form.日期
                });

                if (res.success) {
                    ElMessage.success('基础信息提交成功！');
                    showAddDialog.value = false;
                    // 重置表单
                    form.牌别 = '';
                    form.批次 = '';
                    form.日期 = '';
                    editingRow.value = null;
                    dialogTitle.value = '新增基础信息';
                    // 刷新列表
                    await fetchBasicInfoList();
                } else {
                    ElMessage.error(res.message || '提交失败');
                }
            } catch (error) {
                ElMessage.error(error.message || '提交失败，请重试');
            } finally {
                submitting.value = false;
            }
        }
    });
};

// 对话框关闭时重置表单
const handleDialogClose = () => {
    form.牌别 = '';
    form.批次 = '';
    form.日期 = '';
    editingRow.value = null;
    dialogTitle.value = '新增基础信息';
    if (formRef.value) {
        formRef.value.clearValidate();
    }
};

// 监听对话框关闭
watch(showAddDialog, (newVal) => {
    if (!newVal) {
        handleDialogClose();
    }
});

// 前往评价页面
const goToEvaluation = () => {
    router.push('/evaluation');
};

onMounted(() => {
    getToday();
    fetchBasicInfoList();
});
</script>

<style scoped>
.basic-info-container {
    min-height: 100vh;
    background-color: #f5f5f5;
}

.el-header {
    background-color: #409eff;
    color: white;
    display: flex;
    align-items: center;
    padding: 0 20px;
}

.header-content {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-content h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 500;
}

.date-selector {
    display: flex;
    align-items: center;
}

.el-main {
    padding: 20px;
}

.list-card {
    background: white;
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 500;
    font-size: 16px;
}

.nav-section {
    margin-top: 20px;
    max-width: 500px;
    margin-left: auto;
    margin-right: auto;
}

@media (max-width: 768px) {
    .el-main {
        padding: 15px;
    }

    .header-content {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .date-selector {
        width: 100%;
    }
}
</style>
